package com.apes.hr.group.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.party.model.Person;
import com.apes.scm.masterdata.party.model.RoleType;
import com.apes.scm.masterdata.party.repository.PersonRepository;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 功能：钉钉部门表
 * @author ZhengZX
 * @create 2020年9月15日11:05:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = DingDingDept.CONST_TABLE_NAME)
public class DingDingDept extends Model {
    public static final String CONST_TABLE_NAME = "hr_ding_ding_dept";

    @Id
    @Column(name = "id", nullable = false, length = 120)
    @Comment("编码")
    private String id; //编码

    @Name
    @Column(name = "name", nullable = false, length = 200)
    @Comment("部门名称")
    private String name; //部门名称

    @Column(name = "parent_id", nullable = false, length = 120)
    @Comment("上级部门编码")
    private String parentId; //上级部门ID

    @Column(name = "dept_manager_userid_list", length = 120)
    @Comment("部门的主管列表编码")
    private String deptManagerUseridList; //部门的主管列表

    @Column(name = "group_name", nullable = false, length = 200)
    @Comment("群名称")
    private String groupName; //群名称

    @Column(name = "org_dept_owner", length = 120)
    @Comment("群主人员编码")
    private String orgDeptOwner; //企业群群主编码

    public String getOrgDeptOwner() {
        if (this.orgDeptOwner == null) return null;
        this.orgDeptOwnerTemp = SpringManager.getBean(PersonRepository.class).findAll(
                JpaDsl.toCriteriaByEq(
                        "dingDingUserId", this.orgDeptOwner
                )
        ).stream().findFirst().orElse(null);
        return this.orgDeptOwner;
    }

    @Column(name = "create_dept_group", length = 200, nullable = false)
    @Comment("是否创建部门企业群")
    private boolean createDeptGroup = true;    //是否创建一个关联此部门的企业群，默认为false

    @Column(name = "auto_add_user", length = 200, nullable = false)
    @Comment("自动加群")
    private boolean autoAddUser = false;    //如果有新人加入部门是否会自动加入部门群，默认为false

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "branch_id", referencedColumnName = "id")
    private Branch branch; //行政部门

    @OneToMany(mappedBy = "dingDingDept", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<DingDingDeptDetail> dingDingDeptDetails = new ArrayList(); //钉钉部门规则定义

    public List<DingDingDeptDetail> getDingDingDeptDetails() {
        for (DingDingDeptDetail dingDingDeptDetail : dingDingDeptDetails) {
            dingDingDeptDetail.setDingDingDept(this);
        }
        return dingDingDeptDetails;
    }

    @Transient
    private Person orgDeptOwnerTemp;    //群主人员

    @Transient
    private Set<Person> managerUseridSet;

    public Set<Person> getManagerUseridSet() {
        if (isWrite() || isLoad()) {
            this.managerUseridSet = convertPerson(this.deptManagerUseridList);
        }
        return managerUseridSet;
    }
    public void setManagerUseridSet(Set<Person> managerUseridSet) {
        this.managerUseridSet = managerUseridSet;
        if (!isWrite()) {
            this.deptManagerUseridList = toConvertPerson(this.managerUseridSet);
        }
    }

    //拆分字符串
    private Set<Person> convertPerson(String source) {
        if (StringUtil.isEmpty(source)) return null;
        Set<Person> persons = new HashSet<>();
        String[] rows = source.split("\\|");    //056147580920954696|04211截取成两个钉钉
        for (String person : rows) {
            Person tempPerson = SpringManager.getBean(PersonRepository.class).findAll(
                    JpaDsl.toCriteriaByEq(
                            "dingDingUserId", person
                    )
            ).stream().findFirst().orElse(null);
            persons.add(tempPerson);
        }
        return persons;
    }

    //拼接字符串
    private String toConvertPerson(Set<Person> persons) {
        StringBuffer sb = new StringBuffer();
        for (Person person : persons) {
            sb.append(person.getDingDingUserId());
            sb.append("|");
        }
        if (sb.length()>0){
            sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }
}
